package it.polimi.swKnights.SWIMv2.ejb.administration;

import it.polimi.swKnights.SWIMv2.ejb.authentication.LoginHandlerLocal;
import it.polimi.swKnights.SWIMv2.ejb.entityBeans.Admin;
import it.polimi.swKnights.SWIMv2.ejb.entityBeans.Founder;
import it.polimi.swKnights.SWIMv2.ejb.entityBeans.RegisteredUser;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.InvalidLoginPrivilegesException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.LoginFailException;

import java.util.Date;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;

/**
 * Session Bean implementation class ChangeFounderBean
 */
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class ChangeFounder extends AdministrationBean implements
		ChangeFounderRemote
{
	@EJB
	private LoginHandlerLocal loginController;

	@PersistenceContext(unitName = "swimv2-manager")
	private EntityManager manager;

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public void changeFounder(String founder, String nextFounder,
			String password) throws LoginFailException,
			InvalidLoginPrivilegesException
	{

		this.loginController.checkLoginDataAndPrivileges(founder, password,
				Founder.class);
		this.handleOperation(founder, nextFounder);

	}

	private void handleOperation(String founder, String nextFounder)
	{
		Founder oldFounder = this.manager.getReference(Founder.class, founder);
		RegisteredUser user = this.manager.getReference(RegisteredUser.class,
				nextFounder);

		try
		{
			this.handleFounder(oldFounder);
			this.handleUser(user);
			this.manager.flush();
		}
		catch (Exception e)
		{
			e.printStackTrace();
			System.err.println("Errore in cambio founder");
		}
	}

	private void handleFounder(Founder founder) throws Exception
	{
		Admin exFounder = createUser(founder, Admin.class);
		exFounder.setTookOver(founder.getTookOver());
		this.manager.remove(founder);
		this.manager.persist(exFounder);

	}

	private void handleUser(RegisteredUser user) throws Exception
	{
		Founder newFounder = createUser(user, Founder.class);
		try
		{
			Admin wasAdmin = this.manager.find(Admin.class, user.getUserName());
			if (wasAdmin != null)
				newFounder.setTookOver(wasAdmin.getTookOver());
			else
				newFounder.setTookOver(new Date());
		}
		catch (EntityNotFoundException e)
		{
			newFounder.setTookOver(new Date());
			//brutto ma non funziona altrimenti...
		}

		this.manager.remove(user);
		this.manager.persist(newFounder);
	}

}
